# WebSocket聊天应用本地测试脚本 (不使用Docker)
# 使用方法: .\test-local.ps1

Write-Host "=== WebSocket聊天应用本地测试开始 ===" -ForegroundColor Green

# 检查.NET运行时
Write-Host "检查.NET运行时..." -ForegroundColor Yellow
try {
    $dotnetVersion = dotnet --version
    Write-Host "✅ .NET版本: $dotnetVersion" -ForegroundColor Green
} catch {
    Write-Host "❌ .NET运行时未安装" -ForegroundColor Red
    exit 1
}

# 检查发布文件
Write-Host "检查发布文件..." -ForegroundColor Yellow
if (!(Test-Path "publish\hao-Chat.Api.dll")) {
    Write-Host "❌ 错误: publish\hao-Chat.Api.dll 文件不存在" -ForegroundColor Red
    Write-Host "请先运行: dotnet publish -c Release -o publish" -ForegroundColor Yellow
    exit 1
}

Write-Host "✅ 发布文件检查通过" -ForegroundColor Green

# 检查端口占用
Write-Host "检查端口8083占用情况..." -ForegroundColor Yellow
$portCheck = netstat -an | Select-String ":8083"
if ($portCheck) {
    Write-Host "⚠️ 端口8083已被占用:" -ForegroundColor Yellow
    Write-Host $portCheck -ForegroundColor Gray
    Write-Host "尝试终止占用进程..." -ForegroundColor Yellow
    
    # 尝试找到并终止占用端口的进程
    $processes = Get-NetTCPConnection -LocalPort 8083 -ErrorAction SilentlyContinue
    if ($processes) {
        foreach ($proc in $processes) {
            try {
                Stop-Process -Id $proc.OwningProcess -Force
                Write-Host "✅ 已终止进程 PID: $($proc.OwningProcess)" -ForegroundColor Green
            } catch {
                Write-Host "⚠️ 无法终止进程 PID: $($proc.OwningProcess)" -ForegroundColor Yellow
            }
        }
    }
    Start-Sleep -Seconds 2
}

# 启动应用
Write-Host "启动WebSocket聊天应用..." -ForegroundColor Yellow
Write-Host "应用将在 http://localhost:8083 启动" -ForegroundColor Cyan

# 设置环境变量
$env:ASPNETCORE_ENVIRONMENT = "Production"
$env:ASPNETCORE_URLS = "http://localhost:8083"

# 切换到publish目录并启动应用
Set-Location "publish"

Write-Host "正在启动应用，按 Ctrl+C 停止..." -ForegroundColor Yellow
Write-Host "访问地址: http://localhost:8083" -ForegroundColor Cyan
Write-Host "WebSocket端点: ws://localhost:8083/ws" -ForegroundColor Cyan
Write-Host ""

# 启动应用（非阻塞方式，以便可以测试）
$job = Start-Job -ScriptBlock {
    param($publishPath)
    Set-Location $publishPath
    $env:ASPNETCORE_ENVIRONMENT = "Production"
    $env:ASPNETCORE_URLS = "http://localhost:8083"
    dotnet hao-Chat.Api.dll
} -ArgumentList (Get-Location).Path

# 等待应用启动
Write-Host "等待应用启动..." -ForegroundColor Yellow
Start-Sleep -Seconds 5

# 测试应用响应
Write-Host "测试应用响应..." -ForegroundColor Yellow
try {
    $response = Invoke-WebRequest -Uri "http://localhost:8083" -TimeoutSec 10 -UseBasicParsing
    if ($response.StatusCode -eq 200) {
        Write-Host "✅ 应用启动成功！" -ForegroundColor Green
        Write-Host "✅ HTTP响应正常 (状态码: $($response.StatusCode))" -ForegroundColor Green
        
        # 显示部分响应内容
        $content = $response.Content
        if ($content -match "<title>(.*?)</title>") {
            Write-Host "✅ 页面标题: $($matches[1])" -ForegroundColor Green
        }
        
        Write-Host "`n=== 测试成功 ===" -ForegroundColor Green
        Write-Host "应用正在后台运行，作业ID: $($job.Id)" -ForegroundColor Cyan
        Write-Host "访问地址: http://localhost:8083" -ForegroundColor Cyan
        Write-Host "要停止应用，请运行: Stop-Job $($job.Id); Remove-Job $($job.Id)" -ForegroundColor Yellow
        
    } else {
        Write-Host "⚠️ 应用响应异常，状态码: $($response.StatusCode)" -ForegroundColor Yellow
    }
} catch {
    Write-Host "❌ 无法连接到应用" -ForegroundColor Red
    Write-Host "错误信息: $($_.Exception.Message)" -ForegroundColor Gray
    
    # 检查作业状态
    $jobState = Get-Job -Id $job.Id
    Write-Host "作业状态: $($jobState.State)" -ForegroundColor Gray
    
    if ($jobState.State -eq "Failed") {
        Write-Host "应用启动失败，查看错误信息:" -ForegroundColor Red
        Receive-Job -Id $job.Id
    }
    
    # 清理作业
    Stop-Job -Id $job.Id -ErrorAction SilentlyContinue
    Remove-Job -Id $job.Id -ErrorAction SilentlyContinue
}

# 返回原目录
Set-Location ".."